import { HTTP } from "@/tools"
import { BUSNISSTYPE, DataRule, MENUTYPE, OPENTYPE, PermissionObj, StandardResponse } from "./standard"



export interface LoginUserMenuItem {
  application: string,
  children: LoginUserMenuItem[],
  code: string,
  component: string,
  createTime: string,
  createUser: number,
  icon: string,
  id: string|number,
  link: string,
  name: string,
  openType: OPENTYPE,
  permission: string,
  pid: string,
  pids: string,
  redirect: string,
  remark: string,
  router: string,
  sort: number,
  status: number,
  type: MENUTYPE,
  updateTime: string,
  updateUser: number,
  visible: boolean,
  weight: BUSNISSTYPE
}
export async function getLoginUserMenuList(params: { application: string }) {
  return HTTP.post<StandardResponse<LoginUserMenuItem[]>>('/sysMenu/list', params)
}


export interface MenuSaveInfo extends Partial<PermissionObj> {
  application: string,
  code: string,
  component: string,

  icon: string,
  id?: string,
  link: string,
  name: string,
  openType: OPENTYPE,

  permission: string,
  pid: string,
  pids?: string | (string[]),
  redirect: string,
  remark: string,
  router: string,
  sort: number,
  type: MENUTYPE,
  visible: boolean,
  weight: BUSNISSTYPE
}
export async function saveMenuInfo(params: MenuSaveInfo) {
  const { id } = params
  return HTTP.post(`/sysMenu/${id ? "edit" : "add"}`, params)
}


/**
* 将列表格式化为级联选择项
* @param list  原始用户菜单列表
* @param fliterType 要过滤的菜单类型
* @returns 级联选择项列表
*/

function FormatMenuItemToCascaderOption(list: LoginUserMenuItem[], fliterType: string | (string[]) = ''){
  // 过滤掉指定类型
  const fullMenuList = list.filter(({ type }) => Array.isArray(fliterType) ? !fliterType.includes(type) : type !== fliterType).map(i => {
    // 格式化为级联选择项
    const { id: value, name: label, children } = i
    const tp= { value, label,children:[] }
    if (Array.isArray(children) && children.length) {
      tp.children = FormatMenuItemToCascaderOption(children, fliterType)
    }
    return tp
  })
  return fullMenuList
}
export const getCurrentMenuListToCascaderOption = async (application: string, fliterType: string | (string[]) = '')=> {
  return getLoginUserMenuList({ application })
    .then((d) => FormatMenuItemToCascaderOption(d.data.data, fliterType))
}
export function deleteMenu(row: LoginUserMenuItem) {
  return HTTP.post<StandardResponse>("/sysMenu/delete", { id: row.id })
}